﻿using CatSimulator.Models;
using Loli.Library.Hook;
using Loli.Library.Util;
using Loli.Library.WinForm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CatSimulator
{
    public partial class StepAccount : FormBase
    {

        GameConfig _Config = DataFactory.GetGameConfig();

        public StepAccount()
        {
            InitializeComponent();
#if DEBUG
            tbAccount.Text = "mylovely623@co.kr";
            tbPassword.Text = "dud2850";
            tbSecurityCode.Text = "....+";
#endif
        }

        protected override bool UpdateInfo()
        {
            return CheckTextBox();
        }

        private void butLoginTest_Click(object sender, EventArgs e)
        {
            if (CheckTextBox())
            {

                Task task = new Task(() =>
                {
                    this.Invoke((UpdateInterface)delegate()
                    {
                        butLoginTest.Enabled = false;
                    });

                    this.ShowMessage("运行游戏...");
                    ProcessStartInfo startInfo = new ProcessStartInfo(_Config.GamePath);
                    startInfo.WorkingDirectory = Path.GetDirectoryName(_Config.GamePath);
                    Process.Start(startInfo);
                    Thread.Sleep(1000);

                    var rect = new Loli.Library.Util.WinAPI.Rect();
                    //获取handle
                    IntPtr handle = WinAPI.FindWindow(null, _Config.GameTitle);
                    //获取按钮
                    IntPtr button = WinAPI.FindWindowEx(handle, IntPtr.Zero, null, "게임 실행");

                    if (button != IntPtr.Zero)
                    {
                        this.ShowMessage("点击第一个窗口的按钮...");
                        WinAPI.GetWindowRect(button, ref rect);
                        //移动点击

                        int x = rect.Left + (rect.Right - rect.Left) / 2;
                        int y = rect.Top + (rect.Bottom - rect.Top) / 2;

                        KeyboardMouseOperator.MouseMove(new Point(x, y));
                        Thread.Sleep(200);
                        KeyboardMouseOperator.MouseClick(true);
                    }

                    KeyboardMouseOperator.MouseMove(new Point(0, 0));

                    this.ShowMessage("等待游戏完全载入...");
                    while (true)
                    {
                        //重新获取窗口句柄
                        handle = WinAPI.FindWindow(null, _Config.GameTitle);


                        if (handle == IntPtr.Zero)
                        {
                            Thread.Sleep(5000);
                            continue;
                        }

                        //获取窗口大小
                        WinAPI.GetWindowRect(handle, ref rect);

                        //如果窗口大小小于800*600，那么等待
                        if (rect.Right - rect.Left < 800 || rect.Bottom - rect.Top < 600)
                        {
                            Thread.Sleep(10000);
                        }
                        else
                        {
                            //获取图片
                            using (Bitmap bitmap = ScreenCapturer.Capture(handle))
                            {
                                Random random = new Random();

                                //取3点，同色那么等待
                                Color[] colors = new Color[3];
                                for (int i = 0; i < 3; i++)
                                {
                                    int x = random.Next(50, bitmap.Width - 50);
                                    int y = random.Next(50, bitmap.Height - 50);
                                    colors[i] = bitmap.GetPixel(x, y);
                                }

                                if (colors[0] == colors[1] && colors[1] == colors[2])
                                {
                                    Thread.Sleep(5000);
                                }
                                else
                                {
                                    this.Invoke((UpdateInterface)delegate()
                                    {
                                        picTest.Image = (Bitmap)bitmap.Clone();
                                    });
                                    break;
                                }
                            }
                        }
                    }
                    this.ShowMessage("游戏已经载入，等待片头动画...");
                    //等待15秒
                    Thread.Sleep(15000);
                    _Config.GameHandle = handle;
                    //账户 425*295   
                    //密码 425*320

                    this.ShowMessage("输入账户名...");
                    //获取边框的宽度
                    _Config.BorderWidth = (rect.Right - rect.Left - 800) / 2;
                    _Config.TitleHeight = rect.Bottom - rect.Top - 600 - _Config.BorderWidth;

                    //鼠标移动到账户名
                    int moveX = rect.Left + _Config.BorderWidth + 425;
                    int moveY = rect.Top + _Config.TitleHeight + 295;

                    KeyboardMouseOperator.MouseMove(new Point(moveX, moveY));
                    Thread.Sleep(800);
                    //双击
                    KeyboardMouseOperator.MouseDoubleClick();
                    Thread.Sleep(1000);
                    //输入账户名
                    KeyboardMouseOperator.InputString(_Config.Account);
                    Thread.Sleep(1000);

                    this.ShowMessage("输入密码...");
                    //双击
                    moveY = rect.Top + _Config.TitleHeight + 320;
                    KeyboardMouseOperator.MouseMove(new Point(moveX, moveY));
                    Thread.Sleep(800);
                    KeyboardMouseOperator.MouseDoubleClick();
                    Thread.Sleep(1000);
                    KeyboardMouseOperator.InputString(_Config.Password);
                    Thread.Sleep(1000);

                    this.ShowMessage("登录游戏...");
                    KeyboardMouseOperator.KeyPress(Keys.Enter);
                    Thread.Sleep(5000);

                    this.ShowMessage("进入大区...");
                    KeyboardMouseOperator.KeyPress(Keys.Enter);
                    Thread.Sleep(3000);


                    if (_Config.Channel <= 0)
                    {
                        //随机生成频道
                        _Config.Channel = new Random().Next(1, 20);
                    }

                    this.ShowMessage("选择频道" + _Config.Channel + "...");

                    for (int i = 0; i < _Config.Channel / 5; i++)
                    {
                        KeyboardMouseOperator.KeyPress(Keys.Down);
                        Thread.Sleep(500);
                    }

                    for (int i = 0; i < _Config.Channel % 5; i++)
                    {
                        KeyboardMouseOperator.KeyPress(Keys.Right);
                        Thread.Sleep(500);
                    }
                    KeyboardMouseOperator.KeyPress(Keys.Enter);
                    Thread.Sleep(2000);

                    this.ShowMessage("选择人物...");
                    KeyboardMouseOperator.KeyPress(Keys.Enter);
                    Thread.Sleep(2000);

                    this.ShowMessage("输入安全码...");
                    KeyboardMouseOperator.InputString(_Config.SecurityCode);
                    Thread.Sleep(500);
                    KeyboardMouseOperator.KeyPress(Keys.Enter);
                    Thread.Sleep(2000);
                    this.ShowMessage("登录游戏");

                    this.Invoke((UpdateInterface)delegate()
                    {
                        butLoginTest.Enabled = true;
                    });
                });

                task.Start();

            }
        }

        private void ShowMessage(string str)
        {
            this.Invoke((UpdateInterface)delegate()
            {
                this.labMessage.Text = str;
            });
        }


        private bool CheckTextBox()
        {
            string account = tbAccount.Text.Trim();
            if (string.IsNullOrEmpty(account))
            {
                LoliMessageBox.Show(this, "请输入账号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                tbAccount.Focus();
                return false;
            }


            string password = tbPassword.Text.Trim();
            if (string.IsNullOrEmpty(password))
            {
                LoliMessageBox.Show(this, "请输入密码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                tbPassword.Focus();
                return false;
            }

            string securityCode = tbSecurityCode.Text.Trim();
            if (string.IsNullOrEmpty(securityCode))
            {
                LoliMessageBox.Show(this, "请输入安全码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                tbSecurityCode.Focus();
                return false;
            }


            string channel = tbChannel.Text.Trim();
            if (!string.IsNullOrEmpty(channel))
            {
                _Config.Channel = int.Parse(channel);
            }



            _Config.Account = account;
            _Config.Password = password;
            _Config.SecurityCode = securityCode;

            return true;
        }
    }
}